﻿
Imports System.Web.Http
Imports i_InvoiceApi.Authorization
Imports Microsoft.AspNet.Identity
Imports System.Threading.Tasks

<RoutePrefix("api/Account")>
Public Class AccountController
    Inherits ApiController
    Private _repo As AuthRepository = Nothing

    Public Sub New()
        _repo = New AuthRepository()
    End Sub


    ' POST api/Account/Register
    ''' <summary>
    ''' Use to register users with the identity Framework (OWIN, EntityFramework) 
    ''' use userModel={ 'userName': 'Taiseer','password': 'SuperPass','confirmPassword': 'SuperPass'} a model
    ''' </summary>
    ''' <param name="userModel"></param>
    ''' <returns></returns>
    ''' <remarks></remarks>
    <AllowAnonymous>
    <Route("Register")>
    Public Async Function Register(userModel As UserModel) As Task(Of IHttpActionResult)
        If Not ModelState.IsValid Then
            Return BadRequest(ModelState)
        End If

        Dim result As IdentityResult = Await _repo.RegisterUser(userModel)
        Dim errorResult As IHttpActionResult = GetErrorResult(result)

        If errorResult IsNot Nothing Then
            Return errorResult
        End If

        Return Ok()
    End Function

    Protected Overrides Sub Dispose(disposing As Boolean)
        If disposing Then
            _repo.Dispose()
        End If

        MyBase.Dispose(disposing)
    End Sub

    Private Function GetErrorResult(result As IdentityResult) As IHttpActionResult
        If result Is Nothing Then
            Return InternalServerError()
        End If

        If Not result.Succeeded Then
            If result.Errors IsNot Nothing Then
                For Each [error] As String In result.Errors
                    ModelState.AddModelError("", [error])
                Next
            End If

            If ModelState.IsValid Then
                ' No ModelState errors are available to send, so just return an empty BadRequest.
                Return BadRequest()
            End If

            Return BadRequest(ModelState)
        End If

        Return Nothing
    End Function
End Class
